﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using TConfig;
using tcom.tools;
using System.IO;
using System.Xml;
//using GameInfo;
//using NetWork.ClientNet;

public class FLMClass{
	public 	int sortnum;//下载优先级
	public string objurl;//文件路径
}
	
public class FreeLoaderManager: MonoBehaviour {
	string freeDownloadUrl{
		get{ return GameResources.LocalPath+"xml/AdvLoadSceneObjects.xml";}
	}
	
	List<FLMClass> freedlist=new  List<FLMClass>(); //需要预加载的列表 
	// Use this for initialization
	void Start () {
		Invoke("Init",10);
	}
	void Init()
	{
		//step1 读取需要预加载的物体清单
		ReadFreeDownload(freeDownloadUrl);
		//step3 执行预加载
		InvokeRepeating("FreeLoaderDownloadStart",10,1);	
	}

	public void FreeLoaderDownloadStart()
	{
		//step1 判断当前状态是否是空闲
		if(!bDownloadBusy())
		{
			string nullurl = GetUrlNeedDownLoad();
			if(nullurl.Length>0)
			{

				WebDownload wd = WebDownload.GetInstance();
				if(wd==null)
				{
					Debug.LogError(" wd is null");
				}
				else
				{
					string v = wd.webservername+ nullurl;
					wd.AddDownLoad(v);
				}
			}
			else
			{
				//Debug.LogError("预加载出错了");
			}
		}
		else
		{
			//下载线程忙着呢
		}
	}
 
	/**
	 * 获取第一个要下载的文件
	 */ 
	public string GetUrlNeedDownLoad()
	{
		if(freedlist.Count>0)
		{
			string url = freedlist[0].objurl;
			freedlist.RemoveAt(0);
			
			string bendiurl=GameResources.RootPath+url;
			//string fileName = Path.GetFileNameWithoutExtension(bendiurl).ToLower();	
			string tempfile =bendiurl+".temp";
			//string url = WebDownload.GetInstance().webservername + tempfullname ;
			if(System.IO.File.Exists(tempfile))
			{
				System.IO.File.Delete(tempfile);
			}
			return url;
		}
		else
		{
			return "";
		}
	}
	 
	
	//检查下载线程是否空闲
	public bool bDownloadBusy()
	{
		return WebDownload.GetInstance().IsBusy(3);
	}

	//读取预加载的xml配表
	public void ReadFreeDownload(string url)
	{
		XmlDocument xmlDoc = UnCompress.GetXmlDoc(url, System.Text.Encoding.UTF8);
		XmlNodeList Block = xmlDoc.GetElementsByTagName("SceneObjects");
		
        if (Block.Count > 0)
        {
			XmlElement coun = (XmlElement)Block.Item(0);
			XmlNodeList nodes = coun.GetElementsByTagName("info");
            for (int i = 0; i < nodes.Count; i++)
            {
				XmlElement tg = (XmlElement)nodes.Item(i);
				string file  =tg.GetAttribute("f");
				if(System.IO.File.Exists(GameResources.RootPath+file))
				{
					//已经有了
				}
				else
				{
					FLMClass flm=new FLMClass ();
					flm.sortnum=int.Parse(tg.GetAttribute("pri"));
					flm.objurl= file;
					freedlist.Add(flm);
				}
            }
		 }
	}
	

}
